package org.gongliang.common.base;

import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.gongliang.common.exception.ExceptionEnum;
import org.gongliang.common.mybatis.SqlBuilder;
import org.gongliang.entity.sys.User;
import org.gongliang.kit.str.StrKit;
import org.gongliang.kit.web.WebKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;

import jodd.bean.BeanUtil;

/**
 * 
 * @Description 增删改查控制器
 * @author 龚亮
 * @date 2017年3月30日 下午5:17:01
 */
public abstract class CRUDController<M extends BaseService<T>, T> extends BaseController {

	private String kName;
	public CRUDController(){
		try {
			ParameterizedType pt=(ParameterizedType) this.getClass().getGenericSuperclass();
			@SuppressWarnings("unchecked")
			Class<T> clazz=(Class<T>) pt.getActualTypeArguments()[1];
			kName=clazz.getPackage().getName().substring(clazz.getPackage().getName().lastIndexOf(".")+1)+"/"+clazz.getSimpleName();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
	}
	
	@Autowired
	private M baseService;

	/**
	 * 查询所有(不分页)
	 * 
	 * @return DataGrid
	 */
	@ResponseBody
	@RequestMapping(value = "/findAll", method = { RequestMethod.GET, RequestMethod.POST })
	public Result findAll(HttpServletRequest request) {
		Map<String, Object> reqMap = WebKit.getParams(request);
		List<T> list = baseService.findAll(reqMap);
		Result result = new Result();
		result.setResData(list, list.size());
		return result;
	}

	@ResponseBody
	@RequestMapping(value = "/findAllMap", method = { RequestMethod.GET, RequestMethod.POST })
	public Result findAllMap(HttpServletRequest request) {
		Map<String, Object> reqMap = WebKit.getParams(request);
		List<Map<String, Object>> list = baseService.findAllMap(reqMap);
		Result result = new Result();
		result.setResData(list, list.size());
		return result;
	}


	@ResponseBody
	@RequestMapping(value = "/findById", method = { RequestMethod.GET, RequestMethod.POST })
	public Result findById(String id) {
		Result result = new Result();
		result.setResExtraObj(baseService.findById(id));
		return result;
	}

	/**
	 * 分页查询
	 * 
	 * @return DataGrid
	 */
	@ResponseBody
	@RequestMapping(value = "/findAllByPage", method = { RequestMethod.GET, RequestMethod.POST })
	public Result findAllByPage(HttpServletRequest request) {
		Map<String, Object> reqMap = WebKit.getParams(request);
		List<T> list = baseService.findAll(reqMap);
		WebKit.setPage(WebKit.toPageIndex(reqMap), WebKit.toPageSize(reqMap));
		PageInfo<T> pages = new PageInfo<T>(list);
		Result result = new Result();
		result.setResData(pages.getList(), pages.getTotal());
		return result;
	}

	@ResponseBody
	@RequestMapping(value = "/findAllMapByPage", method = { RequestMethod.GET, RequestMethod.POST })
	public Result findAllMapByPage(HttpServletRequest request) {
		Map<String, Object> reqMap = WebKit.getParams(request);
		List<Map<String, Object>> list = baseService.findAllMap(reqMap);
		WebKit.setPage(WebKit.toPageIndex(reqMap), WebKit.toPageSize(reqMap));
		PageInfo<Map<String, Object>> pages = new PageInfo<Map<String, Object>>(list);
		Result result = Result.success();
		result.setResData(pages.getList(), pages.getTotal());
		return result;
	}

	/**
	 * 添加或者修改 主键id不为空时更新,否则保存
	 */
	@ResponseBody
	@RequestMapping(value = "/saveORupdate", method = RequestMethod.POST)
	public Result saveORupdate(T t) {
		if (t == null) {
			return Result.error(ExceptionEnum.PARAM_NOT_NULL);
		}
		if (t instanceof User && StrKit.isBlank(BeanUtil.declared.getProperty(t, "password"))) {
			String password = new Md5Hash("123456", "", 2).toString();
			BeanUtil.declared.setProperty(t, "password", password);
		}
		if (BeanUtil.declared.getProperty(t, SqlBuilder.getPrimaryKey(t)) != null) {
			baseService.updateById(t);
		} else {
			baseService.save(t);
		}
		return Result.success();
	}

	@ResponseBody
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public Result save(T t) {
		if (baseService.save(t)) {
			return Result.success();
		}
		return Result.error();
	}

	@ResponseBody
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public Result updateById(T t) {
		if (baseService.updateById(t)) {
			return Result.success("更新成功!");
		}
		return Result.error("更新失败!");
	}

	/**
	 * 根据一组id删除
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteIds", method = RequestMethod.POST)
	public Result deleteByIds(T t, @RequestParam(value = "ids[]", required = true) String[] ids) {
		if (ids == null || ids.length == 0) {
			return Result.error(ExceptionEnum.IDS_NOT_NULL);
		}
		if (t instanceof User) {
			if (ArrayUtils.contains(ids, getUser().getId().toString())) {
				return Result.error("当前用户不能删除!");
			}
			if (ArrayUtils.contains(ids, "1")) {
				return Result.error("管理员不能删除!");
			}
		}
		return baseService.deleteByIds(ids) ? Result.success("批量删除成功!") : Result.error("批量删除失败!");
	}

	@ResponseBody
	@RequestMapping(value = "/deleteById", method = { RequestMethod.POST })
	public Result deleteById(T entity, String id) {
		if (StrKit.isBlank(id)) {
			return Result.error(ExceptionEnum.ID_NOT_NULL);
		}
		if (entity instanceof User) {
			if (id.equals(getUser().getId().toString())) {
				return Result.error("当前用户不能删除!");
			}
		}
		return baseService.deleteById(id) ? Result.success("根据id删除成功!") : Result.error("根据id删除失败!");
	}
	
	@GetMapping("/main")
	public String main() {
		return kName+"/main";
	}
}
